//
//  TimeCountDown.swift
//  iOSProjectExtensionSwift
//
//  Created by HBGG on 2020/9/5.
//  Copyright © 2020 lidianchao. All rights reserved.
//

import UIKit

class TimeCountDown: NSObject {
    static func openCountDown(count:TimeInterval,event:@escaping (Int) -> (),cancle: @escaping () -> ()) {
        var timeout = count
        let queue = DispatchQueue.global()//获取全局队列
        let timer = DispatchSource.makeTimerSource(flags: [], queue: queue)//创建计时器
        //计时器回调
        timer.schedule(wallDeadline: DispatchWallTime.now(), repeating: 1, leeway: DispatchTimeInterval.seconds(1))
        timer.setEventHandler {
            timeout = timeout - 1
            if(timeout <= 0) {
                timer.cancel()
            }
            DispatchQueue.main.async {
                event(Int(timeout))
            }
        }
        //倒计时结束回调
        timer.setCancelHandler {
            DispatchQueue.main.async {
                cancle()
            }
        }
        timer.resume()
    }
}
